package cn.smp.client;

import cn.smp.message.*;
import cn.smp.protocol.MessageCodecSharable;
import cn.smp.protocol.ProcaotolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        final CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        final AtomicBoolean LOGIN = new AtomicBoolean();

        final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        final MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        final NioEventLoopGroup worker = new NioEventLoopGroup();
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(worker);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ProcaotolFrameDecoder());
//                ch.pipeline().addLast(LOGGING_HANDLER);
                ch.pipeline().addLast(MESSAGE_CODEC);
                //3s 内如果没有向服务器写数据，会触发一个 IdleState.WRITER_IDLE 事件
                ch.pipeline().addLast(new IdleStateHandler(0,3,0));
                //ChannelDuplexHandler 可以同时作为入站和出站的处理器
                ch.pipeline().addLast(new ChannelDuplexHandler(){
                    // 用来触发特殊事件
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        final IdleStateEvent event = (IdleStateEvent) evt;
                        if (event.state() == IdleState.WRITER_IDLE) {
//                            log.debug("已经 3s 没有写数据了，发送一个心跳包");
                            ctx.writeAndFlush(new PingMessage());
                        }
                    }
                });
                ch.pipeline().addLast("client handler",new ChannelInboundHandlerAdapter(){

                    /**
                     * 在连接建立后触发active事件
                     * @param ctx
                     * @throws Exception
                     */
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        //负责接收用户在控制台的输入，负责向服务器发送各种消息
                        new Thread(() -> {
                            final Scanner scanner = new Scanner(System.in);
                            System.out.println("请输入用户名：");
                            final String username = scanner.nextLine();
                            System.out.println("请输入密码：");
                            final String password = scanner.nextLine();
                            final LoginRequestMessage message = new LoginRequestMessage(username, password);
                            ctx.writeAndFlush(message);
                            System.out.println("等待后续操作...");
                            try {
                                WAIT_FOR_LOGIN.await();
                            } catch (InterruptedException e) {
                                log.error("system in error",e);
                            }
                            if(!LOGIN.get()){
                                ctx.channel().close();
                                return;
                            }

                            //打印菜单
                            menu();

                            while (true){
                                final String command = scanner.nextLine();
                                final String[] s = command.split(" ");
                                switch (s[0]) {
                                    case "send":
                                        ctx.writeAndFlush(new ChatRequestMessage(username,s[1],s[2]));
                                        break;
                                    case "gsend":
                                        ctx.writeAndFlush(new GroupChatRequestMessage(username,s[1],s[2]));
                                        break;
                                    case "gcreate":
                                        final HashSet<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                                        set.add(username);
                                        ctx.writeAndFlush(new GroupCreateRequestMessage(s[1],set));
                                        break;
                                    case "gmembers":
                                        ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                                        break;
                                    case "gjoin":
                                        ctx.writeAndFlush(new GroupJoinRequestMessage(username,s[1]));
                                        break;
                                    case "gquit":
                                        ctx.writeAndFlush(new GroupQuitRequestMessage(username,s[1]));
                                        break;
                                    case "quit":
                                        ctx.channel().close();
                                        return;
                                    case "menu":
                                        menu();
                                        continue;
                                    default:
                                        menu();
                                }
                            }
                        },"system in").start();
                    }

                    private void menu() {
                        System.out.println("============ 功能菜单 ============");
                        System.out.println("send [username] [content]");
                        System.out.println("gsend [group name] [content]");
                        System.out.println("gcreate [group name] [m1,m2,m3...]");
                        System.out.println("gmembers [group name]");
                        System.out.println("gjoin [group name]");
                        System.out.println("gquit [group name]");
                        System.out.println("quit");
                        System.out.println("==================================");
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        log.debug("msg:{}",msg);
                        if ((msg instanceof LoginResponseMessage)) {
                            final LoginResponseMessage responseMessage = (LoginResponseMessage) msg;
                            if (responseMessage.isSuccess()) {
                                //如果登录成功
                                LOGIN.set(true);
                            }
                            WAIT_FOR_LOGIN.countDown();
                        }
                    }
                });
            }
        });
        try {
            final ChannelFuture channelFuture = bootstrap.connect("localhost", 8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("client error",e);
        }finally {
            worker.shutdownGracefully();
        }
    }
}
